package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.mywallet

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import org.json.JSONArray
import org.json.JSONObject

class MyWalletGhanaViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<MyWalletGhanaResult>()
    val pageDetailResult: LiveData<MyWalletGhanaResult> = _pageDetailResult

    /** 获取页面详情接口 */
    fun pageDetail() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "U5nlZIAER9LEMTlxGIBPw"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONArray("obj") ?: JSONArray()
                val list = mutableListOf<JSONObject>()
                for (index in 0 until obj.length()) {
                    val item = obj[index] as JSONObject
                    list.add(item)
                }
                _pageDetailResult.value =
                    MyWalletGhanaResult(items = list)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _pageDetailResult.value = MyWalletGhanaResult(error = errMsg)
            }
        })
    }
}